#!/usr/bin/env python3
"""
创建测试用户脚本
用户名: admin
密码: admin
"""

import asyncio
import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
sys.path.append(str(Path(__file__).parent.parent))

from passlib.context import CryptContext
import asyncpg
from src.core.config import settings

# 密码加密
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

async def create_test_user():
    """创建测试用户"""
    
    # 连接数据库
    conn = await asyncpg.connect(
        host="localhost",
        port=5432,
        user="postgres",
        password="postgres",
        database="ai_writing_db"
    )
    
    try:
        # 检查用户是否已存在
        existing_user = await conn.fetchrow(
            "SELECT id FROM users WHERE username = $1 OR email = $2",
            "admin", "admin@example.com"
        )
        
        if existing_user:
            print("测试用户已存在")
            # 更新密码
            hashed_password = pwd_context.hash("admin")
            await conn.execute(
                """
                UPDATE users 
                SET password_hash = $1, 
                    username = $2,
                    is_active = true,
                    is_superuser = true
                WHERE username = $2 OR email = $3
                """,
                hashed_password, "admin", "admin@example.com"
            )
            print("测试用户密码已更新")
        else:
            # 创建新用户
            hashed_password = pwd_context.hash("admin")
            await conn.execute(
                """
                INSERT INTO users (
                    username, 
                    email, 
                    password_hash, 
                    is_active, 
                    is_superuser,
                    created_at,
                    updated_at
                ) VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
                """,
                "admin", 
                "admin@example.com", 
                hashed_password, 
                True, 
                True
            )
            print("测试用户创建成功")
            
        print("\n登录信息:")
        print("用户名: admin")
        print("邮箱: admin@example.com")
        print("密码: admin")
        print("\n可以使用用户名或邮箱登录")
        
    except Exception as e:
        print(f"错误: {e}")
    finally:
        await conn.close()

if __name__ == "__main__":
    asyncio.run(create_test_user())